<?php

class TaskController extends Controller
{
    public $menu = array(
        array(
            'label' =>  '平台任务',
        ),
        array(
            'label' =>  '查询任务',
            'icon'  =>  'search',
            'url'   =>  array('/task/index', 'type'=>TaskType::Query),
        ),
        array(
            'label' =>  '传输任务',
            'icon'  =>  'random',
            'url'   =>  array('/task/index', 'type'=>TaskType::Transfer),
        ),
        array(
            'label' =>  '计算任务',
            'icon'  =>  'list-alt',
            'url'   =>  array('/task/index', 'type'=>TaskType::Compute),
        ),
    );
    
    /**
     * @return array action filters
     * 
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

	/**
	 * This is the 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
		// renders the view file 'protected/views/site/index.php'
		// using the default layout 'protected/views/layouts/main.php'
        $criteria = new CDbCriteria(array(
        	'with'	=>	array(
		        'job',
		    ),        
            'order' =>  'task_id DESC'
        ));

        if(Yii::app()->user->role == Role::Normal) {
            $criteria->addCondition('job.user_id='.Yii::app()->user->id);
        }

        if(isset($_GET['type'])) {
            $criteria->compare('task_type', intval($_GET['type']));
        }
        if(isset($_GET['job_id'])) {
            $criteria->compare('job.job_id', intval($_GET['job_id']));
        }
        $dataProvider = new CActiveDataProvider('Task', array(
            	'pagination'    =>  array(
                'pageSize'  =>  20,
            ),
            'criteria'  =>  $criteria,
        ));
        $model=new Task;
        if(isset($_GET['Task'])) {
            $model->attributes=$_GET['Task'];
        }
        $this->render('index', array(
            'dataProvider'  => $dataProvider,
            'model'         => $model,
        ));
	}
   
    public function actionKill() {
        if(Yii::app()->request->isAjaxRequest) {
            $id = $_POST['autoId'];
        }
        else {
            if(isset($_GET['id']) && !is_array($_GET['id'])) {
                $id = array($_GET['id']);
            }
        }		
		$shedulerService = SchedulerService::getInstance();
		foreach ($id as $taskId) {
			$status = $shedulerService->addCommand(array(
				'user_id'	=>	Yii::app()->user->id,
				'cmd_type'	=>	CommandType::KillTask,
				'task_id'	=>	$taskId,
				'submit_time'	=>	date('Y-m-d H:i:s'),
				'state'		=>	CmdState::Submit,
			));
			if($status === false) {
				break;
			}
		}
		
        $idList = implode(',', $id);
        if($status) {
        	Yii::log("submit kill task[$idList] command successfully", CLogger::LEVEL_INFO, FRONTEND_LOG);
        }
        else {
        	Yii::log("submit kill task[$idList] command failed", CLogger::LEVEL_ERROR, FRONTEND_LOG);
        }
        if(!Yii::app()->request->isAjaxRequest) {
            $this->redirect(array('index'));
        }

    }

    public function actionRerun() {
        if(Yii::app()->request->isAjaxRequest) {
            $id = $_POST['autoId'];
        }
        else {
            if(isset($_GET['id']) && !is_array($_GET['id'])) {
                $id = array($_GET['id']);
            }
        }

		$shedulerService = SchedulerService::getInstance();
		foreach ($id as $taskId) {
			$status = $shedulerService->addCommand(array(
				'user_id'	=>	Yii::app()->user->id,
				'cmd_type'	=>	CommandType::RerunTask,
				'task_id'	=>	$taskId,
				'submit_time'	=>	date('Y-m-d H:i:s'),
				'state'		=>	CmdState::Submit,
			));
			if($status === false) {
				break;
			}
		}
		
        $idList = implode(',', $id);
        if($status) {
        	Yii::log("submit rerun task[$idList] command successfully", CLogger::LEVEL_INFO, FRONTEND_LOG);
        }
        else {
        	Yii::log("submit rerun task[$idList] command failed", CLogger::LEVEL_ERROR, FRONTEND_LOG);
        }
        if(!Yii::app()->request->isAjaxRequest) {
            $this->redirect(array('index', 'type'=>$_GET['type']));
        }
    }
    
 	public function actionResume() {
 		if(Yii::app()->request->isAjaxRequest) {
            $id = $_POST['autoId'];
        }
        else {
            if(isset($_GET['id']) && !is_array($_GET['id'])) {
                $id = array($_GET['id']);
            }
        }
        $shedulerService = SchedulerService::getInstance();
		foreach ($id as $taskId) {
			$status = $shedulerService->addCommand(array(
				'user_id'	=>	Yii::app()->user->id,
				'cmd_type'	=>	CommandType::ResumeTask,
				'task_id'	=>	$taskId,
				'submit_time'	=>	date('Y-m-d H:i:s'),
				'state'		=>	CmdState::Submit,
			));
			if($status === false) {
				break;
			}
		}
		
 	 	$idList = implode(',', $id);
        if($status) {
        	Yii::log("submit resume task[$idList] command successfully", CLogger::LEVEL_INFO, FRONTEND_LOG);
        }
        else {
        	Yii::log("submit resume task[$idList] command failed", CLogger::LEVEL_ERROR, FRONTEND_LOG);
        }
        if(!Yii::app()->request->isAjaxRequest) {   
            $this->redirect(array('index'));
        }
    }

    /**
	 * This is the 'view' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionView($id)
	{
		// renders the view file 'protected/views/task/view.php'
		// using the default layout 'protected/views/layouts/main.php'
    
        $model = Task::model()->findByPk($id);
        $this->render('view', array(
            'model'  => $model,
        ));
    }
    
	public function actionDelete()
    {
        if(Yii::app()->request->isPostRequest)
        {
			Task::model()->deleteByPk($_GET['id']);
            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if(!isset($_GET['ajax']))
                $this->redirect(array('index'));
        }
        else
            throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
    }

    public function actionAjaxDelete()
    {
        $autoIdAll = $_POST['autoId'];

        if(count($autoIdAll)>0) {
            $count = Task::model()->deleteByPk($autoIdAll);
            $idList = implode(',', $autoIdAll);
            if($count == count($autoIdAll)) {
                Yii::log("task[$idList] was deleted successfully", CLogger::LEVEL_INFO, FRONTEND_LOG);
            }
            else {
                Yii::log("task[$idList] was deleted failed", CLogger::LEVEL_ERROR, FRONTEND_LOG);
            }
        }
    }

}
